#include "writer.h"
#include <QDebug>
#include <QFile>

struct ContentRange {
    qint64 start;      // first byte's index
    qint64 length;     // length of the range
};

ContentRange getContentRange(const QByteArray& header) {
    ContentRange range;
    QString str(header);
    // example header
    // bytes 16133165-19359797/25813069
    int space = str.indexOf(' ');       // space after 'bytes'
    int hyphen = str.indexOf('-');
    int slash = str.indexOf('/');
    QString bytes = str.left(space);
    if(bytes != "bytes") {
        qDebug() << "Content Range is not in bytes";
    }
    QString start = str.mid(space + 1, hyphen - (space + 1));
    range.start = start.toInt();

    QString end = str.mid(hyphen + 1, slash - (hyphen + 1));
    range.length = end.toInt() - range.start + 1;

    qDebug() << start << end << range.length;
    return range;
}

Writer::Writer(QFile *file, QObject *parent)
    : QObject(parent)
{
    this->file = file;
    downloaded = 0;
}

Writer::~Writer()
{
    qDebug("Writer deleted");
}

void Writer::setReply(QNetworkReply *reply)
{
    this->reply = reply;
}

void Writer::bytesAvailable()
{
    // no of bytes available to read
    auto available = reply->bytesAvailable();
    qDebug() << available << "\n";
    auto contentRange = reply->rawHeader("Content-Range");
    qDebug() << "Content-Range:" << contentRange;
    auto range = getContentRange(contentRange);

    auto offset = range.start + downloaded;
    // QByteArray
    auto data = reply->read(available);
    auto x = data.length();
    file->seek(offset);

    qDebug() << "writing file...";
    auto y = file->write(data);
    qDebug() << "finished writing..." << y;

    Q_ASSERT(x == y);

    downloaded += available;
    //qDebug() << "Downloaded: " << downloaded;

    emit newDataDownloaded(available);
}
